<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
import request from '@/utils/request.js'
//导入路由
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

//导入token状态
import { useTokenStore } from '@/stores/token.js'
//调用token状态
const tokenStore = useTokenStore()

const router = useRouter();
//控制注册与登录表单的显示， 默认显示登录
const isRegister = ref(false)

//自定义确认密码的校验函数
const rePasswordValid = (rule, value, callback) => {
    if (value == null || value === '') {
        return callback(new Error('请再次确认密码'))
    }
    if (registerData.value.password !== value) {
        return callback(new Error('两次输入密码不一致'))
    }
    callback()
}
//用于注册的表单校验模型
const registerDataRules = ref({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 16, message: '用户名的长度必须为2~16位', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 16, message: '密码长度必须为5~16位,包含字母和数字', trigger: 'blur' }
    ],
    rePassword: [
        { validator: rePasswordValid, trigger: 'blur' }
    ]
})

// 注册表单的引用
const registerForm = ref(null)
// 登录表单的引用
const loginForm = ref(null)

//用于登录的数据模型
const loginData = ref({
  username: '',
  password: ''
})


//用于注册的数据模型
const registerData = ref({
    username: '',
    password: '',
    rePassword: ''
})

//清空数据模型的数据
const clearRegisterData = () => {
    registerData.value = {
        username: '',
        password: '',
        rePassword: ''
    }
}

import { registerService, loginService } from '@/api/user.js'
import  useUserInfoStore  from '@/stores/userInfo.js'
//用于注册的事件函数
const register = async () => {
    // 先进行表单校验
    try {
        await registerForm.value.validate()
    } catch (error) {
        // 校验失败，不继续执行
        return
    }
    
    try {
        //console.log('注册...');
        await registerService(registerData.value);
        ElMessage.success('注册成功!')
        // 注册成功后切换到登录表单
        isRegister.value = false
        clearRegisterData() // 清空注册表单数据
    } catch (error) {
        // 修改错误处理方式，只传递错误消息
        ElMessage.error(error.message || '注册失败')
    }
}

// 用于登录的事件函数
const login = async () => {
    // 先进行表单校验
    try {
        await loginForm.value.validate()
    } catch (error) {
        // 校验失败，不继续执行
        return
    }
    
    try {
        const response = await loginService(loginData.value)
        // 保存token
        tokenStore.setToken(response.data)
        //打印token
        console.log(response.data);
        ElMessage.success('登录成功!') 
        // 登录成功后跳转到首页
        router.push('/')
    } catch (error) {
        // 修改错误处理方式，只传递错误消息
        ElMessage.error(error.message || '登录失败')
    }
}

</script>

<template>
    <div class="login-container">
        <el-row class="login-page">
            <el-col :span="12" class="bg"></el-col>
            <el-col :span="6" :offset="3" class="form">
                <!-- 注册表单 -->
                <el-form 
                ref="registerForm"
                :model="registerData"
                :rules="registerDataRules"
                autocomplete="off" 
                v-if="isRegister">
                    <el-form-item>
                        <h1>注册</h1>
                    </el-form-item>
                    <el-form-item prop="username">
                        <el-input v-model="registerData.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input v-model="registerData.password" :prefix-icon="Lock" type="password" placeholder="请输入密码"></el-input>
                    </el-form-item>
                    <el-form-item prop="rePassword">
                        <el-input v-model="registerData.rePassword" :prefix-icon="Lock" type="password" placeholder="请输入再次密码"></el-input>
                    </el-form-item>
                    <!-- 注册按钮 -->
                    <el-form-item>
                        <el-button class="button" type="primary" auto-insert-space @click="register">
                            注册
                        </el-button>
                    </el-form-item>
                    <el-form-item class="flex">
                        <el-link type="info" :underline="false" @click="isRegister = false">
                            ← 返回
                        </el-link>
                    </el-form-item>
                </el-form>
                <!-- 登录表单 -->
                <el-form 
                ref="loginForm"
                :model="loginData"
                size="large" 
                autocomplete="off" 
                v-else>
                    <el-form-item>
                        <h1>登录</h1>
                    </el-form-item>
                    <el-form-item>
                        <el-input v-model="loginData.username" :prefix-icon="User" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-input name="password" v-model="loginData.password" :prefix-icon="Lock" type="password" placeholder="请输入密码"></el-input>
                    </el-form-item>
                    <el-form-item class="flex">
                        <div class="flex">
                            <el-checkbox>记住我</el-checkbox>
                            <el-link type="primary" :underline="false">忘记密码？</el-link>
                        </div>
                    </el-form-item>
                    <!-- 登录按钮 -->
                    <el-form-item>
                        <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
                    </el-form-item>
                    <el-form-item class="flex">
                        <el-link type="info" :underline="false" @click="isRegister = true">
                            注册 →
                        </el-link>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </div>
</template>

<style lang="scss" scoped>
/* 样式 */
.login-container {
    width: 100%;
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
}

.login-page {
    width: 100%;
    max-width: 1200px;
    height: 600px;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

    .bg {
        background: url('@assets/images/2.jpg') no-repeat 60% center / 240px auto,
            url('@/assets/images/login.jpg') no-repeat center / cover;
        border-radius: 0 20px 20px 0;
    }

    .form {
        display: flex;
        flex-direction: column;
        justify-content: center;
        user-select: none;

        .title {
            margin: 0 auto;
        }

        .button {
            width: 100%;
        }

        .flex {
            width: 100%;
            display: flex;
            justify-content: space-between;
        }
    }
}

// 当在Layout中显示时的样式调整
:deep(.layout-container) .login-container {
    min-height: calc(100vh - 120px); // 减去header和footer的高度
}

:deep(.layout-container) .login-page {
    margin: 20px;
}
</style>